import sys
import rclpy
from rclpy.node import Node
from gobang_interfaces.srv import Init, Play
import numpy as np
from PyQt5.QtWidgets import QApplication, QMainWindow, QGridLayout, QWidget, QPushButton
from PyQt5.QtCore import Qt

class GobangGUI(QMainWindow):
    def __init__(self):
        super().__init__()
        rclpy.init()
        self.node = Node('gobang_gui_node')
        self.init_service = self.node.create_client(Init, 'gobang_init')
        self.play_service = self.node.create_client(Play, 'gobang_play')
        while not self.init_service.wait_for_service(timeout_sec=1.0):
            self.node.get_logger().info('服务未可用，等待中...')
        while not self.play_service.wait_for_service(timeout_sec=1.0):
            self.node.get_logger().info('服务未可用，等待中...')
        self.init_ui()
        self.init_game()

    def init_ui(self):
        self.setWindowTitle('五子棋')
        self.setGeometry(100, 100, 600, 600)

        central_widget = QWidget(self)
        self.setCentralWidget(central_widget)

        self.grid_layout = QGridLayout(central_widget)
        self.buttons = np.empty((15, 15), dtype=object)  # 假设棋盘大小为 15x15
        for i in range(15):
            for j in range(15):
                button = QPushButton('', self)
                button.setFixedSize(40, 40)
                button.clicked.connect(lambda _, r=i, c=j: self.make_move(r, c))
                self.grid_layout.addWidget(button, i, j)
                self.buttons[i, j] = button

    def init_game(self):
        request = Init.Request()
        request.is_first = True
        request.difficulty = 3
        future = self.init_service.call_async(request)
        rclpy.spin_until_future_complete(self.node, future)
        if future.result() is not None:
            self.update_board(future.result().board)

    def make_move(self, row, col):
        request = Play.Request()
        request.row = row
        request.col = col
        future = self.play_service.call_async(request)
        rclpy.spin_until_future_complete(self.node, future)
        if future.result() is not None:
            self.update_board(future.result().board)

    def update_board(self, board):
        board = np.array(board).reshape(15, 15)
        for i in range(15):
            for j in range(15):
                if board[i, j] == 'O':
                    self.buttons[i, j].setText('O')
                elif board[i, j] == 'X':
                    self.buttons[i, j].setText('X')
                else:
                    self.buttons[i, j].setText('')

    def closeEvent(self, event):
        rclpy.shutdown()
        event.accept()

# if __name__ == '__main__':
def main():
    app = QApplication(sys.argv)
    gui = GobangGUI()
    gui.show()
    sys.exit(app.exec_())
